/*
Copyright (c)2009 Seesmic, Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.seesmic.twhix
{
	import flash.utils.Dictionary;
	
	public class Roster
	{
		public var items:Dictionary = new Dictionary();
		protected var conn:XMPP;
		
		public function Roster(conn:XMPP)
		{
			this.conn = conn;
		}
		
		public function updatePresence(jid:JID, type:String, status:String='', priority:String=null):void {
			if(!items.hasOwnProperty(barejid)) {
				newItem(jid);
			}
			var barejid:String = jid.getBareJID();
			var resource:String = jid.getResource();
			items[barejid]['presence'][resource] = new Dictionary();
			items[barejid]['presence'][resource]['type'] = type;
			items[barejid]['presence'][resource]['status'] = status;
			if(priority) {
				items[barejid]['presence'][resource]['priority'] = priority;
			}
		}
		
		public function updateItem(jid:JID, subscription:String='none', nick:String='', groups:Array=null):Dictionary {
			return newItem(jid, subscription, nick, groups);
		}
		
		private function newItem(jid:JID, subscription:String='not-in-list', nick:String='', groups:Array=null):Dictionary {
			var barejid:String = jid.getBareJID();
			if(!items.hasOwnProperty(barejid)) {
				items[barejid] = new Dictionary();
				items[barejid]['presence'] = new Dictionary();
				items[barejid]['jid'] = barejid;
			}
			items[barejid]['subscription'] = subscription;
			items[barejid]['nick'] = nick;
			items[barejid]['groups'] = groups;
			items[barejid]['name'] = nick;
			if(!items[barejid]['name']) items[barejid]['name'] = barejid;
			return items[barejid];
		}
		
		public function getHighestStatus(jid:String):Dictionary {
			if(!items.hasOwnProperty(jid)) return null;
			var toppriority:Number = -99999;
			var topresource:Dictionary;
			for(var resource:String in items[jid]['presence']) {
				if(Number(items[jid]['presence'][resource]['priority']) > toppriority) {
					toppriority = Number(items[jid]['presence'][resource]['priority']);
					topresource = items[jid]['presence'][resource]
				}
			}
			if(!topresource) {
				topresource = new Dictionary;
				topresource['type'] = 'unavailable';
				topresource['status'] = '';
				topresource['priority'] = '0';
			}
			return topresource;
		}
	}
}
